package com.czy.util.json;

import com.czy.convert.Converter;
import com.czy.util.time.TimeFormat;
import com.czy.util.time.TimeUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.time.LocalDate;

/**
 * jason转对象时，日期字符串转date对象。
 *
 * @author chenzy
 * @since 2019.12.25
 */

public class DeserializerStr2LocalDate extends JsonDeserializer<LocalDate> implements Converter<String, LocalDate> {
    @Override
    public LocalDate deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        return convert(p.getText());
    }

    @Override
    public LocalDate convert(String source) {
        if (source != null && source.length() > 10) {
            source = source.substring(0, 10);
        }
        return TimeUtil.str2Date(source, TimeFormat.yyyy_MM_dd).orElse(null);
    }
}
